package com.example.match.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.example.match.R;
import com.example.mylibrary.util.ResourcesUtils;

/**
 * Created by fairplay on 2018/5/29.
 */

public class LoadDialog {
    private static Dialog dialog;
    private static View dialogView;

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static void showDialog(Context context, String message) {
        //防止快速显示,新对象覆盖旧对象,导致旧对象的关闭不了
        dismssDialog();
        if(canShowDialog(context)){
            dialogView = ResourcesUtils.findViewById(context, R.layout.load_dialog);
            TextView tvMessage = (TextView) dialogView.findViewById(R.id.tv_dialog_msg);
            if (!TextUtils.isEmpty(message)) {
                tvMessage.setText(message);
            }
            dialog = new AlertDialog.Builder(context, R.style.Dialog).create();
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
            dialog.setContentView(dialogView);
        }
    }

    public static void dismssDialog() {
        try {
            if (null != dialog && dialog.isShowing()) {
                dialog.dismiss();
                dialog = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static boolean canShowDialog(Context context) {
        if (context instanceof Activity) {
            Activity activity = (Activity) context;
            return !activity.isFinishing();
        } else {
            return false;
        }
    }
}
